package com.thinkit.cms.service.template;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.thinkit.cms.api.fragment.FragmentModelService;
import com.thinkit.cms.api.site.SiteTemplateService;
import com.thinkit.cms.api.template.PartLoopHelp;
import com.thinkit.cms.api.template.TempLoopHelp;
import com.thinkit.cms.api.template.TemplateService;
import com.thinkit.cms.api.template.TemplateTypeService;
import com.thinkit.cms.dto.fragment.FragmentModelDto;
import com.thinkit.cms.dto.template.TemplateDto;
import com.thinkit.cms.dto.template.TemplateTypeDto;
import com.thinkit.cms.entity.fragment.FragmentModel;
import com.thinkit.cms.entity.template.Template;
import com.thinkit.cms.mapper.template.TemplateMapper;
import com.thinkit.core.base.BaseServiceImpl;
import com.thinkit.core.constant.Constants;
import com.thinkit.core.handler.CustomException;
import com.thinkit.directive.emums.DirectiveEnum;
import com.thinkit.directive.emums.MethodEnum;
import com.thinkit.utils.model.ApiResult;
import com.thinkit.utils.model.PageDto;
import com.thinkit.utils.model.TreeFileModel;
import com.thinkit.utils.properties.ThinkItProperties;
import com.thinkit.utils.utils.Checker;
import com.thinkit.utils.utils.FileLoopUtil;
import com.thinkit.utils.utils.Md5;
import com.thinkit.utils.utils.XMLParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipInputStream;

/**
 * <p>
 * 模板表 服务实现类
 * </p>
 *
 * @author lg
 * @since 2020-07-23
 */
@Transactional
@Service
public class TemplateServiceImpl extends BaseServiceImpl<TemplateDto, Template, TemplateMapper> implements TemplateService {

    @Autowired
    ThinkItProperties thinkItProperties;

    @Autowired
    SiteTemplateService siteTemplateService;

    @Autowired
    TemplateTypeService templateTypeService;

    @Autowired
    FragmentModelService fragmentModelService;


    @Override
    public PageDto<TemplateDto> listPage(PageDto<TemplateDto> pageDto){
        IPage<TemplateDto> pages = new Page<>(pageDto.getPageNo(), pageDto.getPageSize());
        pageDto.getDto().setRoleSigns(getRoleSign()).setCreateId(getUserId());
        IPage<TemplateDto> result = baseMapper.listPage(pages, pageDto.getDto());
        PageDto<TemplateDto> resultSearch = new PageDto(result.getTotal(), result.getPages(), result.getCurrent(), Checker.BeNotEmpty(result.getRecords()) ? result.getRecords() : Lists.newArrayList());
        return resultSearch;
    }




    @Override
    public void save(TemplateDto v) {
        ckLegal(null,v.getTemplateCode());
        String templatePath=thinkItProperties.getTemplate()+ File.separator+v.getTemplateCode();
        v.setTemplateFolderPath(Constants.SEPARATOR+v.getTemplateCode());
        mkdirDirectories(Arrays.asList(templatePath));
        super.insert(v);
    }

    @CacheEvict(value = Constants.cacheName, key = "#root.targetClass+'.getByPk.'+#p0.id")
    @Override
    public void update(TemplateDto v) {
       TemplateDto templateDto =getByPk(v.getId());
       ckLegal(v.getId(),v.getTemplateCode());
       String templatePath=thinkItProperties.getTemplate()+ File.separator+v.getTemplateCode();
       if(!templateDto.getTemplateCode().equals(v.getTemplateCode())){
           if(isDirectory(templatePath)){
               FileUtil.rename(new File(templatePath),v.getTemplateCode(),true);
               // 修改网站对应模板的位置
               siteTemplateService.updateTempLocation(templateDto.getId(),Constants.SEPARATOR+v.getTemplateCode());
           }else{
               mkdirDirectories(Arrays.asList(templatePath));
           }
       }
       v.setTemplateFolderPath(Constants.SEPARATOR+v.getTemplateCode());
       super.updateByPk(v);
    }

    @Override
    public List<TreeFileModel> loadTemplateTree(String templateId) {
        String telpLocation = baseMapper.getTempLoaction(thinkItProperties.getTemplate(),templateId);
        if(Checker.BeNotBlank(telpLocation)){
            telpLocation= telpLocation.replace("\\","/");
        }
        List<TreeFileModel> files=FileLoopUtil.loopLoadFiles(telpLocation,thinkItProperties.getTemplate(),new TempLoopHelp(fragmentModelService,templateId));
        List<TreeFileModel> root = new ArrayList<>();
        TreeFileModel treeFileModel=new TreeFileModel();
        String md5Key = Md5.md5(telpLocation);
        treeFileModel.setChildren(files).setKey(md5Key).setValue(md5Key).
        setRelativePath(telpLocation.replace(thinkItProperties.getTemplate().replace("\\","/"),"")).setIsLeaf(false).
        setPath(telpLocation).setDisabled(true).setTitle("根目录");
        root.add(treeFileModel);
        return root;
    }


    @Override
    public List<TreeFileModel> loadPartFile(String templateId) {
        String telpLocation = baseMapper.getTempLoaction(thinkItProperties.getTemplate(),templateId);
        List<TreeFileModel> files=FileLoopUtil.loopLoadFiles(telpLocation,thinkItProperties.getTemplate(),new PartLoopHelp(fragmentModelService,templateId));
        List<TreeFileModel> root = new ArrayList<>();
        recursion(root,files);
        return root;
    }

    @Override
    public ApiResult importFile(String path, List<MultipartFile> files) throws IOException {
        if(Checker.BeNotBlank(path) && FileUtil.exist(path)){
            for(MultipartFile file:files){
                FileUtil.writeFromStream(file.getInputStream(),new File(path+"/"+file.getOriginalFilename()));
            }
            return ApiResult.result();
        }
        return ApiResult.result(20042);
    }

    @Override
    public ApiResult unZipFile(String path) {
        if(Checker.BeNotBlank(path) && FileUtil.exist(path) && FileUtil.isFile(path) && FileUtil.getSuffix(path).equals("zip")){
            try {
                ZipUtil.unzip(new ZipInputStream(FileUtil.getInputStream(path)), new File(FileUtil.file(path).getParent()));
                return ApiResult.result();
            }catch (Exception e){
                return ApiResult.result(20043);
            }
        }
        return ApiResult.result(20043);
    }



    private void recursion(List<TreeFileModel> root,List<TreeFileModel> childs){
        if(Checker.BeNotEmpty(childs)){
            for(TreeFileModel fileModel:childs){
                if(fileModel.getFile().isFile() && fileModel.getIsFragment()){
                    root.add(fileModel);
                }
                recursion(root,fileModel.getChildren());
            }
        }
    }


    @Override
    public ApiResult getFileContent(String path) {
        if(isFile(path)){
            String fileContent = FileUtil.readString(new File(path), Constants.DEFAULT_CHARSET_NAME);
            return ApiResult.result(fileContent);
        }
        return ApiResult.result("");
    }

    @Override
    public boolean setFileContent(String path, String content) {
        if(isFile(path)){
            content = Checker.BeNotNull(content)?content:"";
            FileUtil.writeString(content,new File(path), Charset.forName("UTF-8"));
        }
        return true;
    }

    @Override
    public boolean createFile(String path, String fileName,Integer type) {
        if(fileName.startsWith(Constants.DEFAULT_FRAGMENT_PREFIX)){
            throw new CustomException(ApiResult.result(5026));
        }
        String realPath = path+File.separator+fileName;
        if(isDirectory(path)){
            if(type==0){// 文件
                try {
                    String filePath = realPath+Constants.DEFAULT_HTML_SUFFIX;
                    if(isFile(filePath)){
                        throw new CustomException(ApiResult.result(5025));
                    }
                    FileUtil.newFile(filePath).createNewFile();
                } catch (IOException e) {
                    log.error("创建文件失败:"+e.getMessage());
                }
            }else{//文件夹目录
                FileUtil.mkdir(realPath);
            }
        }else{
            if(!FileUtil.exist(path)){
                throw new CustomException(ApiResult.result(5035));
            }
        }
        return true;
    }

    @Transactional
    @Override
    public boolean delFile(String path) {
        if(isFile(path) || isDirectory(path)){
           deleFragment(new File(path));
           return FileUtil.del(path);
        }
        return false;
    }

    @Override
    public ApiResult checkerIsStartTemplate(String templateId) {
        Integer count = baseMapper.getStartTemplate(getSiteId(),templateId);
        if(count==0){
            return ApiResult.result(5028);
        }
        return ApiResult.result();
    }

    @Transactional
    @Override
    public ApiResult uploadFile(List<MultipartFile> files) {
        String path ="",tempL="";
        if(Checker.BeNotEmpty(files)){
            for(MultipartFile file:files){
                checkFileSuffix(file.getOriginalFilename());
                try {
                    tempL=thinkItProperties.getTemplate()+Constants.SEPARATOR+Md5.md5(file.getOriginalFilename())+".zip";
                    File tempFolder=new File(tempL);
                    if(!tempFolder.exists()){
                        tempFolder.createNewFile();
                    }else{
                        FileUtil.del(tempL);
                        tempFolder.createNewFile();
                    }
                    Boolean isWindow = System.getProperty("os.name").toLowerCase().contains("windows");
                    String charset="UTF-8";
                    if(isWindow){
                        charset="GBK";
                    }
                    FileUtil.writeFromStream(file.getInputStream(),tempFolder);
                    File zipFile=ZipUtil.unzip(tempFolder,Charset.forName(charset));
                    path=zipFile.getAbsolutePath();
                    File configFile =ckHasConfig(zipFile);
                    if(Checker.BeNotNull(configFile)){
                        TemplateDto template=insertParseXml(configFile,zipFile);
                        if(Checker.BeNotNull(template)){
                            FileUtil.rename(new File(zipFile.getAbsolutePath()),template.getTemplateCode(),true);
                        }
                    }
                }catch (Exception e) {
                    if(Checker.BeNotBlank(path)){
                        FileUtil.del(path);
                    }
                    if(Checker.BeNotBlank(tempL)){
                        FileUtil.del(tempL);
                    }
                    log.error(e.getMessage());
                    throw new CustomException(ApiResult.result(20043));
                }finally {
                    if(Checker.BeNotBlank(path)){
                        FileUtil.del(path);
                    }
                    if(Checker.BeNotBlank(tempL)){
                        FileUtil.del(tempL);
                    }
                }
            }
        }
        return ApiResult.result();
    }

    private TemplateDto insertParseXml(File xml, File zipFile){
        if(xml.exists()){
            TemplateDto template = parseXml(xml);
            checkJsonData(template);
            if(Checker.BeNotBlank(template.getId())){
                template.setId(id());
            }
            super.deleteByPk(template.getId());
            super.insert(template);
            if(Checker.BeNotEmpty(template.getFragmentModels())){
                fragmentModelService.deleteByFiled("template_id",template.getId());
                List<FragmentModelDto> fragmentModels=template.getFragmentModels();
                for(FragmentModelDto fragmentMode:fragmentModels){
                    if(Checker.BeNotBlank(fragmentMode.getFileName())){
                        fragmentModelService.deleteByFiled("file_name",fragmentMode.getFileName());
                    }
                    fragmentMode.setTemplateId(template.getId());
                }
                fragmentModelService.insertBatch(fragmentModels);
            }
            return template;
        }
        return null;
    }



    private TemplateDto parseXml(File file){
        TemplateDto template = new TemplateDto();
        try {
            // 创建saxReader对象
            SAXReader reader = new SAXReader();
            Document document = reader.read(file);
            Element configs = document.getRootElement();
            String tid= configs.element("id").getText();
            String name= configs.element("name").getText();
            String sourceFolder= configs.element("sourceFolder").getText();
            String templateCode= configs.element("templateCode").getText();
            String price= configs.element("price").getText();
            String isShare= configs.element("isShare").getText();
            String developerContact= configs.element("developerContact").getText();
            String developerName= configs.element("developerName").getText();
            template.setSourceFolder(sourceFolder).setPrice(price).setTemplateCode(templateCode).setIsShare("true".equals(isShare)).
            setDeveloperContact(developerContact).setDeveloperName(developerName).setName(name).
            setTemplateFolderPath("/"+templateCode).setId(tid);
            Element fragmentDatas = configs.element("fragmentDatas");
            if(Checker.BeNotNull(fragmentDatas) && fragmentDatas.hasContent()){
                List<FragmentModelDto> fragmentModels = new ArrayList<>();
                Iterator<Element> elementIterator=  fragmentDatas.elementIterator("fragmentData");
                while (elementIterator.hasNext()){
                    FragmentModelDto fragmentMode = new FragmentModelDto();
                    Element fragmentData = elementIterator.next();
                    String id = fragmentData.element("id").getText();
                    String alias = fragmentData.element("alias").getText();
                    String code = fragmentData.element("code").getText();
                    String fileName = fragmentData.element("fileName").getText();
                    String defaultFieldList = fragmentData.element("defaultFieldList").getText();
                    String extendFieldList = fragmentData.element("extendFieldList").getText();
                    String allFieldList = fragmentData.element("allFieldList").getText();
                    String requiredFieldList = fragmentData.element("requiredFieldList").getText();
                    String fieldTextMap = fragmentData.element("fieldTextMap").getText();
                    fragmentMode.setAlias(alias).setCode(code).setFileName("null".equals(fileName)?null:fileName).
                    setDefaultFieldList("null".equals(defaultFieldList)?null:defaultFieldList).
                    setExtendFieldList("null".equals(extendFieldList)?null:extendFieldList).
                    setAllFieldList("null".equals(allFieldList)?null:allFieldList).
                    setRequiredFieldList("null".equals(requiredFieldList)?null:requiredFieldList).
                    setFieldTextMap("null".equals(fieldTextMap)?null:fieldTextMap).setId(id);
                    fragmentModels.add(fragmentMode);
                }
                template.setFragmentModels(fragmentModels);
            }
            return template;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return template;
    }


    @Override
    public void exportit(String tempId, HttpServletResponse response) {
        String telpLocation = baseMapper.getTempLoaction(thinkItProperties.getTemplate(),tempId);
        if(Checker.BeNotBlank(telpLocation)){
            if(FileUtil.exist(telpLocation)){
                String tempFilePath = thinkItProperties.getTemplate()+Constants.SEPARATOR+"template.zip";
                try {
                    //ckHasTempConfig(tempId,telpLocation);
                    createXml(tempId,telpLocation);
                    ZipUtil.zip(telpLocation,tempFilePath , false);
                    down(tempFilePath,response);
                }catch (Exception e){
                    log.error(e.getMessage());
                }finally {
                    FileUtil.del(tempFilePath);
                }
            }
        }
    }


    @Override
    public void downFiles(String path, HttpServletResponse response) {
        File downFile = new File(path);
        if(downFile.exists()){
            try {
                if(downFile.isDirectory()){
                   downFile = ZipUtil.zip(path,thinkItProperties.getTemplate()+".zip" , false);
                }
                down(downFile.getPath(),response);
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
    }

    @Cacheable(value = Constants.cacheName, key = "#root.targetClass+'.'+#root.methodName" , unless="#result == null")
    @Override
    public ApiResult getDirects() {
        List<Map<String, String>> directives=new ArrayList<>(16);
        Element element= XMLParser.parserElement("directs.xml");
        List<Element> directs=element.elements("direct");
        for (DirectiveEnum directiveNameEnum : DirectiveEnum.values()) {
            directives.add(buildDirectMap(directiveNameEnum.getName(),directiveNameEnum.getCode(),
            directiveNameEnum.getValue(),directs));
        }
        for (MethodEnum methodEnum : MethodEnum.values()) {
            directives.add(buildDirectMap(methodEnum.getName(),null,
            methodEnum.getValue(),directs));
        }
        return ApiResult.result(directives);
    }



    private  Map<String, String> buildDirectMap(String name,String code,String value,List<Element> directs){
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        map.put("name", name);
        map.put("value", value);
        map.put("example", getDirectsExample(value,directs));
        return map;
    }

    private String getDirectsExample(String value,List<Element> directs){
        String example="";
        for (Element direct : directs){
            String name=direct.elementText("name");
            if(value.equals(name)){
                Element directElement=direct.element("example");
                String directExample=directElement.getText();
                if(Checker.BeNotBlank(directExample)){
                    example=directExample.replace("《","<").replace("》",">").replace("&amp;","&");
                }
            }
        }
        return example;
    }

    private void createXml(String tempId,String tempPath){
        List<File> files = FileUtil.loopFiles(tempPath);
        if(Checker.BeNotEmpty(files)){
            TemplateDto templateDto = baseMapper.findTempConfig(tempId);
            if(Checker.BeNotNull(templateDto)){
                templateDto.setTypeIds(null).setRoleSigns(null);
                String xmlFile =tempPath+Constants.SEPARATOR+"config.xml";
                buildDom(templateDto,xmlFile);
            }
        }
    }

    private void ckHasTempConfig(String tempId,String tempPath){
        List<File> files = FileUtil.loopFiles(tempPath);
        if(Checker.BeNotEmpty(files)){
          boolean hasConf = false;
          for(File file:files){
              if(file.isFile() && "config.json".equals(file.getName())){
                  hasConf = true;
                  break;
              }
          }
          if(!hasConf){
              TemplateDto templateDto = baseMapper.findTempConfig(tempId);
              if(Checker.BeNotNull(templateDto)){
                  templateDto.setTypeIds(null).setRoleSigns(null);
                  String xmlFile =tempPath+Constants.SEPARATOR+"config.xml";
                  buildDom(templateDto,xmlFile);
//                  String configStr=JSONUtil.toJsonStr(templateDto);
//                  File file = FileUtil.newFile(tempPath+Constants.SEPARATOR+"config.json");
//                  FileUtil.writeString(configStr,file,Charset.forName("UTF-8"));
              }
          }
        }
    }


    private void buildDom(TemplateDto template , String xmlPath){
        List<FragmentModelDto> fragmentModels=fragmentModelService.listByField("template_id",template.getId());
        File xmlFile = FileUtil.newFile(xmlPath);
        // 创建一个根节点
        Document document = DocumentHelper.createDocument();
        Element configs = document.addElement("configs");
        Element tid = configs.addElement("id");
        tid.setText(template.getId());
        Element name = configs.addElement("name");
        name.setText(template.getName());
        Element sourceFolder = configs.addElement("sourceFolder");
        sourceFolder.setText(template.getSourceFolder());
        Element templateCode = configs.addElement("templateCode");
        templateCode.setText(template.getTemplateCode());
        Element price =configs.addElement("price");
        price.setText(template.getPrice());
        Element isShare =configs.addElement("isShare");
        isShare.setText(template.getIsShare().toString());
        Element developerContact =configs.addElement("developerContact");
        String devContactText=Checker.BeBlank(template.getDeveloperContact())?"暂无":template.getDeveloperContact();
        developerContact.setText(devContactText);
        Element developerName =configs.addElement("developerName");
        developerName.setText(template.getDeveloperName());
        // 设置模板的页面片段
        Element  fragmentDatas = configs.addElement("fragmentDatas");
        if(Checker.BeNotEmpty(fragmentModels)){
            for(FragmentModelDto fragmentModel:fragmentModels){
                Element fragmentData = fragmentDatas.addElement("fragmentData");
                Element id =fragmentData.addElement("id");
                id.setText(fragmentModel.getId());

                Element alias = fragmentData.addElement("alias");
                alias.setText(fragmentModel.getAlias());

                Element code =fragmentData.addElement("code");
                code.setText(fragmentModel.getCode());

                Element fileName = fragmentData.addElement("fileName");
                fileName.setText(Checker.BeNotBlank(fragmentModel.getFileName())?fragmentModel.getFileName():"null");

                Element defaultFieldList = fragmentData.addElement("defaultFieldList");
                defaultFieldList.setText(Checker.BeNotBlank(fragmentModel.getDefaultFieldList())?fragmentModel.getDefaultFieldList():"null");

                Element extendFieldList = fragmentData.addElement("extendFieldList");
                extendFieldList.setText(Checker.BeNotBlank(fragmentModel.getExtendFieldList())?fragmentModel.getExtendFieldList():"null");

                Element allFieldList = fragmentData.addElement("allFieldList");
                allFieldList.setText(Checker.BeNotBlank(fragmentModel.getAllFieldList())?fragmentModel.getAllFieldList():"null");

                Element requiredFieldList = fragmentData.addElement("requiredFieldList");
                requiredFieldList.setText(Checker.BeNotBlank(fragmentModel.getRequiredFieldList())?fragmentModel.getRequiredFieldList():"null");

                Element fieldTextMap = fragmentData.addElement("fieldTextMap");
                fieldTextMap.setText(Checker.BeNotBlank(fragmentModel.getFileName())?fragmentModel.getFileName():"null");
            }
        }


        // 5、设置生成xml的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置编码格式
        format.setEncoding("UTF-8");
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(xmlFile);
            XMLWriter xmlWriter = new XMLWriter(fileWriter,format);
            // 设置是否转义，默认使用转义字符
            xmlWriter.setEscapeText(false);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private File down(String filePath,HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        if(file.exists()){
            InputStream in = null;
            OutputStream out = null;
            response.setCharacterEncoding(Constants.DEFAULT_CHARSET_NAME);
            response.setHeader("content-disposition","attachment;fileName="+file.getName());
            response.setHeader("FileName", file.getName());
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            try {
                out=  response.getOutputStream();
                in = new FileInputStream(file);
                byte[] buffer  = new byte[1024];
                int i=in.read(buffer );
                while (i!=-1){
                    out.write(buffer , 0, i);//将缓冲区的数据输出到浏览器
                    i= in.read(buffer );
                }
            } catch (IOException e) {
                throw e;
            }finally {
                in.close();
                out.close();
            }
        }
        return file;
    }

    private void doInsertTemp(File configFile,File zipPath){
        String content = FileUtil.readString(configFile,Charset.forName("utf-8"));
        if(Checker.BeNotBlank(content)){
            TemplateDto templateDto = JSONUtil.toBean(content,TemplateDto.class);
            checkJsonData(templateDto);
            templateDto.setTemplateFolderPath(Constants.SEPARATOR+templateDto.getTemplateCode());
            String zipFilePath = thinkItProperties.getTemplate()+Constants.SEPARATOR+templateDto.getTemplateCode();
            if(FileUtil.exist(zipFilePath)){
                //baseMapper.deleteByCode(templateDto.getTemplateCode());
                //FileUtil.del(zipFilePath);
                zipPath.delete();
                throw new CustomException(ApiResult.result(5041));
            }else{
                FileUtil.rename(zipPath,templateDto.getTemplateCode(),true);
                if(Checker.BeNotBlank(templateDto.getTypeCode())){
                    TemplateTypeDto typeDto= templateTypeService.getByCode(templateDto.getTypeCode());
                    templateDto.setTypeId(typeDto.getId());
                }
                super.insert(templateDto);
            }

        }
    }

    private void checkJsonData(TemplateDto templateDto){
        if(Checker.BeNull(templateDto)){
            throw new CustomException(ApiResult.result(5040));
        }
        if(Checker.BeBlank(templateDto.getSourceFolder())){
            throw new CustomException(ApiResult.result(5042));
        }
        if(Checker.BeBlank(templateDto.getTemplateCode())){
            throw new CustomException(ApiResult.result(5043));
        }
    }

    private File ckHasConfig(File folder){
        File configFile = null;
        boolean res =false;
        File[] files = folder.listFiles();
        if(files.length==1){
            files = files[0].listFiles();
        }
        if(folder.listFiles().length>0){
            for(File file:files){
                if(file.isFile()&&file.getName().contains("config.xml")){
                    res = true;
                    configFile = file;
                    break;
                }
            }
        }else{
            res= false;
        }
        if(!res){
            folder.delete();
            throw new CustomException(ApiResult.result(5040));
        }
        return configFile;
    }

    private void checkFileSuffix(String fileName){
        if(!"zip".equals(FileUtil.getSuffix(fileName))){
            throw new CustomException(ApiResult.result(5039));
        }
    }

    private void deleFragment(File file){
        if(file.getName().startsWith(Constants.DEFAULT_FRAGMENT_PREFIX)){
            fragmentModelService.deleteFile(getFragmentId(file.getName()));
        }
    }
    private String getFragmentId(String fileName){
        if(Checker.BeNotBlank(fileName)){
            String id =fileName.replace(Constants.DEFAULT_FRAGMENT_PREFIX,"").
            replace(Constants.DEFAULT_HTML_SUFFIX,"");
            return id;
        }
        return "";
    }


    private boolean isFile(String path){
        boolean isLegal = FileUtil.exist(path) && FileUtil.isFile(path);
        return isLegal;
    }


    private boolean isDirectory(String path){
        boolean isLegal = FileUtil.exist(path) && FileUtil.isDirectory(path) && Checker.BeNotBlank(path);
        return isLegal;
    }

    private void ckLegal(String id,String code){
       Integer count = baseMapper.hashTempCode(id,code);
       if(count>0){
           throw new CustomException(ApiResult.result(5019));
       }
    }

    private void mkdirDirectories(List<String> directories){
        if(Checker.BeNotEmpty(directories)){
            for(String directorie:directories){
                boolean isCreate = Checker.BeNotBlank(directorie) && !FileUtil.exist(directorie);
                if(isCreate){
                    FileUtil.mkdir(directorie);
                }
            }
        }
    }
}
